package com.mybatis;

import com.foreknow.model.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;


public class TsetUser {

    @Test
    public void getUserByIdTset() throws IOException {
    //读取并解析配置文件SqlMapConfig.xml
        String resource = "SqlMapConfig.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        //获取会话工厂SqlSessionFactory 作用:可以调用里面的方法进行增删改查的操作
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //开启
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //根据id查询,调用映射文件中的sql  test表示命名空间namespace  getUserById  标签中的id
        User user = sqlSession.selectOne("test.getUserById",1);
        System.out.println(user.getUsername()+"----"+user.getAddress());
        //关闭
        sqlSession.close();
    }
    @Test
    public void insertUserTest() throws IOException {
        String resource = "SqlMapConfig.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        User user = new User();
        user.setUsername("李宝库");
        user.setBirthday(new Date());
        user.setSex("1");
        user.setAddress("北京市朝阳区");
        int a = sqlSession.insert("test.insertUser",user);
        //增删改查需要提交事务
        sqlSession.commit();
        System.out.println(a);
        //释放资源
        sqlSession.close();
    }
    @Test
    public void deleteUserById() throws IOException {
        String resource = "SqlMapConfig.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        int a = sqlSession.delete("test.deleteUserById",26);
        sqlSession.commit();
        System.out.println(a);
        sqlSession.close();

    }
}
